package com.luo.sc.oidc.authserver.handler.login;

import com.luo.sc.oidc.authserver.enums.AuthenticaionResultCodeEnum;
import com.luo.sc.oidc.authserver.utils.HttpContextUtils;
import com.luo.sc.oidc.authserver.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 通用登录 - 失败处理器 - 返回失败响应结果（支持Ajax）
 *
 * @author Luohq
 * @date 2022-03-11
 * @see org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler
 */
@Slf4j
public class UniLoginRespJsonAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        log.debug("UniLogin authentication failure - {}", exception.getMessage());
        //构建认证失败的响应结果
        String respJson = JsonUtils.toJson(UniLoginRespJsonDto.builder()
                .code(AuthenticaionResultCodeEnum.FAILURE.getCode())
                .msg(exception.getMessage())
                .build());
        log.debug("UniLogin authentication failure resp: {}", respJson);
        HttpContextUtils.responseJson(respJson, response);
    }
}
